import re
import os
import json
import time
import random
import requests
import threading
from urllib.parse import urljoin
from urllib.parse import urlparse
from urllib.parse import urlparse, parse_qs
from requests.exceptions import RequestException
from requests.exceptions import ConnectionError, Timeout

# 实时日志
def EcxlbMhb(message, flush=False):
    print(f"{message}", flush=flush)

# 新增函数：提交检测文章到验证接口
def submit_detection_article(url, token):
    """
    提交检测文章到验证接口
    :param url: 需要过检测的文章URL
    :param token: 用户token (用于日志标识)
    :return: 是否验证成功
    """
    # 验证接口地址
    DETECTION_URL = "http://192.168.10.104:5000/zdgjc"
    
    max_retries = 3
    for attempt in range(max_retries):
        try:
            payload = {"url": url}
            response = requests.post(
                DETECTION_URL,
                json=payload,
                timeout=30,
                headers={"Content-Type": "application/json"}
            )
            
            # 检查响应状态
            if response.status_code == 200:
                result = response.json()
                if result.get("code") == 200:
                    print(f"✅ 检测文章验证成功 (尝试 {attempt+1}/{max_retries})", flush=True)
                    return True
            
            # 记录非200响应
            print(f"❗检测文章验证失败 (尝试 {attempt+1}/{max_retries}): HTTP {response.status_code}", flush=True)
            print(f"响应内容: {response.text}", flush=True)
            
        except Exception as e:
            print(f"❗检测文章验证异常 (尝试 {attempt+1}/{max_retries}): {str(e)}", flush=True)
        
        # 重试前等待
        if attempt < max_retries - 1:
            time.sleep(random.uniform(5, 7))
    
    return False

# 主程序
def process_account(account, i):
    max_retries = 1
    uas = account.split("&")[0][-3:]
    token = account.split("&")[2]
    ysmuid, unionid = account.split("&")[:2]
    # 获取域名 
    current_url = requests.get("https://www.filesmej.cn/waidomain.php", timeout=5).json()["data"]["luodi"]
    session = requests.Session()
    headers = {
        "Connection": "keep-alive",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": f"{UA} {uas}",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/wxpic,image/tpg,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "X-Requested-With": "com.tencent.mm",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        "Cookie": f"ysmuid={ysmuid}"
    }
    for _ in range(11):
        try:
            parsed = urlparse(current_url)
            headers["Host"] = parsed.netloc
            response = session.get(current_url, headers=headers, allow_redirects=False, timeout=10)
            if response.status_code in (301, 302, 303, 307, 308):
                current_url = urljoin(current_url, response.headers.get("Location", ""))
            else:
                break
        except (requests.RequestException, requests.exceptions.InvalidURL) as e:
            print(f"❗重定向错误: {e}", flush=True)
            break
        try:
            parsed_domain = urlparse(current_url).netloc.lstrip("www.")
        except Exception as e:
            print(f"❗域名获取失败: {e}", flush=True)
    # 验证用户
    codeid = lambda: (
        (match.group(1) if (match := re.compile(r'codeid\s*=\s*"(\d+)"').search(
            requests.get(
                f"http://{parsed_domain}/?inviteid=0",
                headers = {
                    "Host": f"{parsed_domain}",
                    "Connection": "keep-alive",
                    "Upgrade-Insecure-Requests": "1",
                    "User-Agent": f"{UA} {uas}",
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/wxpic,image/tpg,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                    "X-Requested-With": "com.tencent.mm",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": f"ysmuid={ysmuid}"
                },
                timeout=10
            ).text
        )) else print("❗警告：未找到codeid", flush=True)) 
        if not any([
            print(f"❗网络请求失败: {e}", flush=True) if isinstance(e, requests.RequestException) else
            print(f"❗正则错误: {e}", flush=True) if isinstance(e, re.error) else
            print(f"❗未知错误: {e}", flush=True) for e in [Exception][:0]
        ]) else None
    )
    codeid = codeid()
    # 获取id
    extract_dynamic_id = lambda: (
        (match.group(1) if (match := re.compile(r'我的id:(\d+)').search(
            requests.get(
                f"http://{parsed_domain}/?inviteid=0",
                headers = {
                    "Host": f"{parsed_domain}",
                    "Connection": "keep-alive",
                    "Upgrade-Insecure-Requests": "1",
                    "User-Agent": f"{UA} {uas}",
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/wxpic,image/tpg,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                    "X-Requested-With": "com.tencent.mm",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": f"ysmuid={ysmuid}"
                },
                timeout=10
            ).text
        )) else print("❗警告：未找到ID", flush=True)) 
        if not any([
            print(f"❗网络请求失败: {e}", flush=True) if isinstance(e, requests.RequestException) else
            print(f"❗正则错误: {e}", flush=True) if isinstance(e, re.error) else
            print(f"❗未知错误: {e}", flush=True) for e in [Exception][:0]
        ]) else None
    )
    # 开始阅读        
    print(f"\n{'=' * 10}🔰🔰开始执行账号{i}🔰🔰{'=' * 10}\n", flush=True)
    print("👌👌 账号验证成功", flush=True)
    time.sleep(1)
    url = f"http://{parsed_domain}/yunonline/v1/gold"
    headers = {
        "Host": f"{parsed_domain}",
        "Connection": "keep-alive",
        "User-Agent": f"{UA} {uas}",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "X-Requested-With": "XMLHttpRequest",
        "Referer": f"http://{parsed_domain}/",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        "Cookie": f"ysmuid={ysmuid}; ejectCode=1"
    }
    params = {
        "unionid": f"{unionid}",
        "time": int(time.time() * 1000)
    }
    response = requests.get(url, headers=headers, params=params).json()
    if response["errcode"] == 0:
        day_gold = response["data"]["day_gold"]
        day_read = response["data"]["day_read"]
        last_gold = response["data"]["last_gold"]
        remain_read = response["data"]["remain_read"]
        print(f"🙍🙍 ID:{extract_dynamic_id()}", flush=True)
        print(f"💰 当前金币:{last_gold}\n📖📖 今日已读:{day_read}  剩余:{remain_read}", flush=True)
        print("🔔🔔 自动提现已关闭" if money_Withdrawal == 0 else "🔔🔔 自动提现已开启", flush=True)
        print(f"{'=' * 10}📖📖开始阅读文章📖📖{'=' * 10}\n", flush=True)
        for i in range(33):
            current_timestamp = int(time.time() * 1000)
            checkDict = [
                "MzkzMTYyMDU0OQ==",
                "Mzk0NDcxMTk2MQ==",
                "MzkzNTYxOTgyMA==",
                "MzkzNDYxODY5OA==",
                "MzkwNzYwNDYyMQ==",
                "MzkyNjY0MTExOA==",
                "MzkwMTYwNzcwMw==",
                "Mzg4NTcwODE1NA==",
                "MzkyMjYxNzQ2NA==",
            ]
            time.sleep(1)
            url = f"http://{parsed_domain}/wtmpdomain2"
            headers = {
                "Host": f"{parsed_domain}",
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "User-Agent": f"{UA} {uas}",
                "X-Requested-With": "XMLHttpRequest",
                "Origin": f"http://{parsed_domain}",
                "Referer": f"http://{parsed_domain}/?inviteid=0",
                "Accept-Encoding": "gzip, deflate",
                "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                "Cookie": f"ysmuid={ysmuid};ejectCode=1"
            }
            data = {
                "unionid": unionid
            }
            for retry in range(max_retries):
                try:
                    response = requests.post(url, headers=headers, data=data, timeout=7).json()
                    break
                except (ConnectionError, Timeout):
                    if retry < max_retries - 1:
                        time.sleep(2.5)
                        continue
                    else:
                        print("❗网络异常退出", flush=True)
                        break
                except Exception as e:
                    print(e, flush=True)
                    if retry < max_retries - 1:
                        print("❗状态1异常，尝试重新发送请求...", flush=True)
                        time.sleep(2.5)
                        continue
                    else:
                        print("❗达到最大重试次数，退出", flush=True)
                        break
            if response["errcode"] == 0:
                time.sleep(1)
                parsed_url = response['data']['domain']
                url_parts = urlparse(parsed_url)
                gt = parse_qs(url_parts.query).get('gt', [''])[0]
                new_url = f"{url_parts.scheme}://{url_parts.netloc}/xdaeryy?gt={gt}&time={current_timestamp}&psgn=168&vs=120"
                headers = {
                    "Host": f"{url_parts.netloc}",
                    "Connection": "keep-alive",
                    "User-Agent": f"{UA} {uas}",
                    "Accept": "application/json, text/javascript, */*; q=0.01",
                    "X-Requested-With": "XMLHttpRequest",
                    "Referer": f"{url_parts.scheme}://{url_parts.netloc}/xsysy.html?{url_parts.query}",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Accept-Encoding": "gzip, deflate"                             
                }
                for retry in range(max_retries):
                    try:
                        response = requests.get(new_url, headers=headers, timeout=7).json()
                        break
                    except (ConnectionError, Timeout):
                        if retry < max_retries - 1:
                            time.sleep(2.5)
                            continue
                        else:
                            print("❗网络异常退出", flush=True)
                            break
                    except Exception as e:
                        print(e, flush=True)
                        if retry < max_retries - 1:
                            print("❗状态2异常，尝试重新发送请求...", flush=True)
                            time.sleep(2.5)
                            continue
                        else:
                            print("❗达到最大重试次数，退出", flush=True)
                            break
                if response["errcode"] == 0:
                    link = response['data']['link']
                    if link:
                        biz_match = re.search(r'__biz=([^&]+)', link)
                        biz = biz_match.group(1) if biz_match else "❗未知来源文章"
                        sleep = random.randint(8, 25)
                        delay = random.randint(30, 90)
                        print(f"✅ 第{int(day_read)+ i + 1}篇文章获取成功---文章来源--- {biz}", flush=True)
                        print(f"📖📖 开始阅读: {link}", flush=True)
                        if biz == "❗未知来源文章" or biz in checkDict:
                            print(f"❗❗❗发现检测文章--- {biz}", flush=True)
                            print(f"📌 检测文章链接: {link}", flush=True)
                            
                            # 提交到检测接口
                            if not submit_detection_article(link, token):
                                print("❗❗❗检测文章验证失败，终止当前账号任务", flush=True)
                                break  # 终止阅读循环
                            
                            # 等待阅读完成
                            print(f"🕗🕗🕗{delay}秒后继续运行…", flush=True)
                            time.sleep(delay)
                            
                            url = f"{url_parts.scheme}://{url_parts.netloc}/jinbicp?gt={gt}&time={sleep}&timestamp={current_timestamp}"
                            headers = {
                                "Host": f"{url_parts.netloc}",
                                "Connection": "keep-alive",
                                "User-Agent": f"{UA} {uas}",
                                "Accept": "application/json, text/javascript, */*; q=0.01",
                                "X-Requested-With": "XMLHttpRequest",
                                "Referer": f"{url_parts.scheme}://{url_parts.netloc}/xsysy.html?{url_parts.query}",
                                "Accept-Encoding": "gzip, deflate",
                                "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
                            }
                            for retry in range(max_retries):
                                try:
                                    response = requests.get(url, headers=headers, timeout=7).json()
                                    break
                                except (ConnectionError, Timeout):
                                    if retry < max_retries - 1:
                                        time.sleep(2.5) 
                                        continue
                                    else:
                                        print("❗网络异常退出", flush=True)
                                        break
                                except Exception as e:
                                    print('❗提交状态异常', flush=True)
                                    print(e)
                            if response["errcode"] == 0:
                                gold = response['data']['gold']
                                print(f"✅ 第{i + 1}次阅读检测文章成功---获得金币:💰{gold}💰", flush=True)
                                print(f"{'-' * 60}\n")
                            else:
                                print(f"❗❗❗过检测失败\n{response}", flush=True)
                                break
                        else:
                            time.sleep(sleep)
                            url = f"{url_parts.scheme}://{url_parts.netloc}/jinbicp?gt={gt}&time={sleep}&timestamp={current_timestamp}"
                            headers = {
                                "Host": f"{url_parts.netloc}",
                                "Connection": "keep-alive",
                                "User-Agent": f"{UA} {uas}",
                                "Accept": "application/json, text/javascript, */*; q=0.01",
                                "X-Requested-With": "XMLHttpRequest",
                                "Referer": f"{url_parts.scheme}://{url_parts.netloc}/xsysy.html?{url_parts.query}",
                                "Accept-Encoding": "gzip, deflate",
                                "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
                            }
                            for retry in range(max_retries):
                                try:
                                    response = requests.get(url, headers=headers, timeout=7).json()
                                    break
                                except (ConnectionError, Timeout):
                                    if retry < max_retries - 1:
                                        time.sleep(2.5)
                                        continue
                                    else:
                                        print("❗网络异常退出", flush=True)
                                        break
                                except Exception as e:
                                    print("❗提交状态异常", flush=True)
                                    print(e)
                            if response["errcode"] == 0:
                                gold = response["data"]["gold"]
                                print(f"📖📖 本次模拟阅读{sleep}秒", flush=True)
                                print(f"✅ 第{i + 1}次阅读成功---获得金币:💰{gold}💰", flush=True)
                                print(f"{'-' * 60}\n")
                            else:
                                print(f"❗阅读文章失败，请尝试重新运行\n{response}", flush=True)
                                break
                    else:
                        print("❗未找到link")
                elif response["errcode"] == 405:
                    print(f"❗{response}", flush=True)
                    print(f"❗请尝试重新运行", flush=True)
                    break
                elif response["errcode"] == 407:
                    if '<br />1、' in response["msg"]:
                        first_part = response["msg"].split('<br />1、', 1)[0]
                        first_rule = response["msg"].split('<br />1、', 1)[1].split('<br />')[0].strip()
                        print(f"❗{first_part}", flush=True)
                        print(f"❗{first_rule}", flush=True)
                        break
                    else:
                        print(f"❗{response['msg']}", flush=True)
                        break
                else:
                    print(f"⚠️ 未知错误 {response['errcode']}: {response}", flush=True)
                    break
            else:
                print(f"❗获取文章失败{response}", flush=True)
                break
        # 提现
        if money_Withdrawal == 1:
            if int(last_gold) > 5000:
                print(f"{'=' * 12}💰开始提现💰{'=' * 12}\n", flush=True)
                url = f"http://{parsed_domain}"
                headers = {
                    "Host": f"{parsed_domain}",
                    "Connection": "keep-alive",
                    "Cache-Control": "max-age=0",
                    "Upgrade-Insecure-Requests": "1",
                    "User-Agent": f"{UA} {uas}",
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/wxpic,image/tpg,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                    "X-Requested-With": "com.tencent.mm",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": f"ysmuid={ysmuid}"
                }
                response = requests.get(url, headers=headers).text
                res1 = re.sub('\s', '', response)
                exchangeUrl = re.findall('"target="_blank"href="(.*?)">提现<', res1)
                eurl = exchangeUrl[0]
                query_dict = parse_qs(urlparse(exchangeUrl[0]).query)
                unionids = query_dict.get('unionid', [''])[0]
                request_id = query_dict.get('request_id', [''])[0]
                b = urlparse(eurl)
                host=b.netloc
                url = f"http://{host}/yunonline/v1/gold"
                headers = {
                    "Host": f"{host}",
                    "Connection": "keep-alive",
                    "User-Agent": f"{UA} {uas}",
                    "Accept": "application/json, text/javascript, */*; q=0.01",
                    "X-Requested-With": "XMLHttpRequest",
                    "Referer": f"{eurl}",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": f"ysmuid={ysmuid}; ejectCode=1"
                }
                params = {
                    "unionid": f"{unionid}",
                    "time": int(time.time() * 1000)
                }
                response = requests.get(url, headers=headers, params=params).json()
                if response["errcode"] == 0:
                    last_gold = response["data"]["last_gold"]
                    gold = int(int(last_gold) / 1000) * 1000
                url = f"http://{host}/yunonline/v1/user_gold"
                headers = {
                    "Host": f"{host}",
                    "Accept": "application/json, text/javascript, */*; q=0.01",
                    "X-Requested-With": "XMLHttpRequest",
                    "User-Agent": f"{UA} {uas}",
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "Origin": f"http://{host}",
                    "Referer": f"{eurl}",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": f"ysmuid={ysmuid}"
                }
                data = {
                    "unionid": unionids,
                    "request_id": request_id,
                    "gold": gold,
                }
                response = requests.post(url, headers=headers, data=data).json()
                print(f"💰 当前可提现:{gold}", flush=True)
                url = f"http://{host}/yunonline/v1/withdraw"
                headers = {
                    "Host": f"{host}",
                    "Connection": "keep-alive",
                    "Accept": "application/json, text/javascript, */*; q=0.01",
                    "X-Requested-With": "XMLHttpRequest",
                    "User-Agent": f"{UA} {uas}",
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "Origin": f"http://{host}",
                    "Referer": f"{eurl}",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": f"ysmuid={ysmuid}"
                }
                data = {
                    "unionid": unionids,
                    "signid": request_id,
                    "ua": "2",
                    "ptype": "0",
                    "paccount": "",
                    "pname": ""
                }
                response = requests.post(url, headers=headers, data=data)
                data = response.json()
                if data["errcode"] == 0:
                    print("💰 恭喜您，提现成功！\n", flush=True)
                else:
                    print(f"❗{response}", flush=True)
            else:
                print(f"{'=' * 17}{'=' * 17}", flush=True)
                print("🔔🔔 金币不足5000，不执行提现\n", flush=True)
        elif money_Withdrawal == 0:
            print(f"{'=' * 17}{'=' * 17}", flush=True)
            print(f"🔔🔔 自动提现已关闭，不执行提现\n", flush=True)
    else:
        print(f"❗获取用户信息失败", flush=True)
        exit()


def notice():
    try:
        print(requests.get("https://gitee.com/gngkj/wxyd/raw/master/label.txt", timeout=5).text)
    except requests.RequestException as e:
        print(f"❗网络异常，获取通知时出错: {e}")


if __name__ == "__main__":
    notice()
    accounts = os.getenv("xyy")
    money_Withdrawal = 0 if os.getenv("xyytx", "0") == "0" else 1
    if (UA := os.getenv("UA")) is None: print("❗未找到变量UA", flush=True); exit()
    if accounts is None: print("❗未找到变量xyy", flush=True); exit()
    else:
        accounts_list = accounts.split("@")
        num_of_accounts = len(accounts_list)
        print(f"\n获取到 {num_of_accounts} 个账号", flush=True)
        for i, account in enumerate(accounts_list, start=1):
            process_account(account, i)

if __name__ == '__main__': pass
